package top.mollysu.sell.aspects;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.mollysu.sell.exception.SellAuthorizeException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author kosmosr
 * @Date 2018/3/25
 */
@Aspect
@Component
@Log4j2
public class UserAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(* top.mollysu.sell.controller.seller.*.*(..))" +
            "&& !execution(* top.mollysu.sell.controller.seller.SellerUserController.*(..))")
    public void verifyUser() {
    }

    @Before("verifyUser()")
    public void doverify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Cookie[] cookies = request.getCookies();
        Map<String, Cookie> cookieMap = new HashMap<>();
        for (Cookie cookie : cookies) {
            cookieMap.put(cookie.getName(), cookie);
        }

        Cookie cookie = null;
        //cookie
        if (!cookieMap.containsKey("token")) {
            log.error("【登录校验】Cookie中查不到token");
            throw new SellAuthorizeException();
        } else {
            cookie = cookieMap.get("token");
        }

        //redis
        String result = redisTemplate.opsForValue().get("token_" + cookie.getName());
        if (StringUtils.isEmpty(result)) {
            log.error("【登录校验】Redis中查不到token");
            throw new SellAuthorizeException();
        }
    }
}
